<template>
  <el-dialog v-model="dialogVisible" title="编辑调查" width="50%">
    <el-form :model="surveyForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="调查标题" prop="title">
        <el-input v-model="surveyForm.title" placeholder="请输入调查标题"/>
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input-number v-model="surveyForm.amount" :min="0" placeholder="请输入金额"></el-input-number>
      </el-form-item>

      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="surveyForm.quantity" :min="0" placeholder="请输入数量"></el-input-number>
      </el-form-item>

      <el-form-item label="单价" prop="unitPrice">
        <el-input-number v-model="surveyForm.unitPrice" :min="0" placeholder="请输入单价"></el-input-number>
      </el-form-item>

      <el-form-item label="总折扣价" prop="totalDiscountPrice">
        <el-input-number v-model="surveyForm.totalDiscountPrice" :min="0" placeholder="请输入总折扣价"></el-input-number>
      </el-form-item>

      <el-form-item label="条件" prop="condition">
        <el-input v-model="surveyForm.condition" placeholder="请输入条件"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input v-model="surveyForm.content" type="textarea" placeholder="请输入内容" :rows="4"></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="surveyForm.description" type="textarea" placeholder="请输入描述" :rows="4"></el-input>
      </el-form-item>

      <el-form-item label="参与人数" prop="participantCount">
        <el-input-number v-model="surveyForm.participantCount" :min="0" placeholder="请输入参与人数"></el-input-number>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="surveyForm.createTime" type="datetime" placeholder="请选择创建时间"></el-date-picker>
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="surveyForm.endTime" type="datetime" placeholder="请选择结束时间"></el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="surveyForm.status" placeholder="请选择状态">
          <el-option label="进行中" value="ongoing"></el-option>
          <el-option label="已结束" value="ended"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <div style="display:flex;gap: 10px;flex-direction: column" class="layout">
    <el-button type="success" @click="handleCreate">创建调查</el-button>
    <div style="display:flex;gap: 10px;flex-wrap: wrap">
      <el-card style="flex: 1;min-width: 300px" v-for="(item,idx) in surveyData">
        <div style="display:flex;flex-direction: column;align-items: center;gap: 10px">
          <el-text size="small" type="info">{{item.createType === 'admin' ? '官方问卷' : '用户问卷'}}</el-text>
          <el-avatar :size="100" :src="item.createType === 'admin' ? 'imgs/1.png' : 'imgs/2.png'" />
          <el-text size="large" type="info">{{item.title}}</el-text>
          <div style="margin: 0 10px;display: flex;flex-direction: column;padding: 10px 0;background: #f0f0f0;width: 100%;border-radius: 10px;align-items: start;">
            <el-text style="width: 90%;" size="small" type="info">No.{{item.surveyId}}</el-text>
            <el-text style="width: 90%;" size="small" type="info">内容: {{item.content}}</el-text>
            <el-text style="width: 90%;" size="small" type="info">单价: {{item.amount}}</el-text>
          </div>
        </div>
        <template #footer>
          <el-button size="small" v-if="item.surveyId === authStore.uid" type="warning" @click="handleEdit(item)">编辑</el-button>
          <el-button size="small" v-if="item.surveyId === authStore.uid" type="primary" @click="handleView(item)">详情</el-button>
          <el-button size="small" v-else @click="handleViewWrite(item)">填写问卷</el-button>
          <el-button size="small" v-if="item.surveyId === authStore.uid" type="danger" @click="deleteSurvey(item.surveyId)">删除</el-button>
        </template>
      </el-card>
    </div>

  </div>
  <!-- 创建按钮 -->
</template>

<script setup lang="ts">
import {defineProps, ref, reactive, onMounted, watch} from 'vue';
import { ElMessage } from 'element-plus';
import instance from "@/utils/http";
import {useRouter} from "vue-router";
import {useAuthStore} from "@/stores/auth";


const authStore = useAuthStore();

interface Survey {
  surveyId: number;
  amount: number;
  quantity: number;
  unitPrice: number;
  totalDiscountPrice: number;
  title: string;
  condition: string;
  content: string;
  creatorId: number;
  participantCount: number;
  createTime: string;
  endTime: string;
  status: string;
  description: string;
  createType:string;
}

const surveyData = ref<Survey[]>([]);

const surveyForm = reactive({
  surveyId: 0,
  amount: 0,
  quantity: 0,
  unitPrice: 0,
  totalDiscountPrice: 0,
  title: '',
  condition: '',
  content: '',
  creatorId: authStore.uid,
  participantCount: 0,
  createTime: '',
  endTime: '',
  status: 'ongoing',
  description: '',
  createType:"user"
});

const dialogVisible = ref(false);

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入调查标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  totalDiscountPrice: [{ required: true, message: '请输入总折扣价', trigger: 'blur' }],
  createTime: [{ required: true, message: '请选择创建时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 获取所有调查数据
const fetchSurveys = async () => {
  try {
    const response = await instance.get('/surveys');
    surveyData.value = response.data.data;
  } catch (error) {
    ElMessage.error('无法加载调查数据');
  }
};

// 创建调查
const createSurvey = async () => {
  try {
    const response = await instance.post('/surveys', surveyForm);
    ElMessage.success('调查创建成功');
    fetchSurveys();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('创建调查失败');
  }
};

// 更新调查
const updateSurvey = async () => {
  try {
    const response = await instance.put(`/surveys/${surveyForm.surveyId}`, surveyForm);
    ElMessage.success('调查更新成功');
    fetchSurveys();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新调查失败');
  }
};

// 删除调查
const deleteSurvey = async (surveyId: number) => {
  try {
    const response = await instance.delete(`/surveys/${surveyId}`);
    ElMessage.success('调查删除成功');
    fetchSurveys();
  } catch (error) {
    ElMessage.error('删除调查失败');
  }
};

// 编辑调查
const handleEdit = (row: Survey) => {
  surveyForm.surveyId = row.surveyId;
  surveyForm.amount = row.amount;
  surveyForm.quantity = row.quantity;
  surveyForm.unitPrice = row.unitPrice;
  surveyForm.totalDiscountPrice = row.totalDiscountPrice;
  surveyForm.title = row.title;
  surveyForm.condition = row.condition;
  surveyForm.content = row.content;
  surveyForm.creatorId = row.creatorId;
  surveyForm.participantCount = row.participantCount;
  surveyForm.createTime = row.createTime;
  surveyForm.endTime = row.endTime;
  surveyForm.status = row.status;
  surveyForm.description = row.description;
  surveyForm.createType = row.createType;
  dialogVisible.value = true;
};

const router = useRouter()
// 查看调查详情
const handleView = (row: Survey) => {
  router.push({ name: 'SurveyDetail', params: { surveyId:row.surveyId } });
};

const handleViewWrite = (row: Survey) => {
  router.push({ name: 'WriteSurey', params: { surveyId:row.surveyId } });
}

// 创建按钮点击事件
const handleCreate = () => {
  surveyForm.surveyId = 0;
  surveyForm.title = '';
  surveyForm.amount = 0;
  surveyForm.quantity = 0;
  surveyForm.unitPrice = 0;
  surveyForm.totalDiscountPrice = 0;
  surveyForm.condition = '';
  surveyForm.content = '';
  surveyForm.creatorId = authStore.uid;
  surveyForm.participantCount = 0;
  surveyForm.createTime = '';
  surveyForm.endTime = '';
  surveyForm.status = 'ongoing';
  surveyForm.description = '';
  surveyForm.createType = "user"
  console.log(surveyForm)
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  if (surveyForm.surveyId === 0) {
    createSurvey();
  } else {
    updateSurvey();
  }
};

onMounted(()=>{
  fetchSurveys()
})

</script>

<style scoped>
</style>
